/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.container;

import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.DnDConstants;
import java.util.Enumeration;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

/**
 * DNDTree
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public class DNDTree extends JTree {

  private static final long serialVersionUID = 7392786906458747071L;
  Insets autoscrollInsets = new Insets(20, 20, 20, 20); // insets

  public DNDTree() {
    setAutoscrolls(true);
    setRootVisible(true);
    setShowsRootHandles(false);// to show the root icon
    getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); // set single selection for
                                                                                            // the Tree
    setEditable(false);
    new DefaultTreeTransferHandler(this, DnDConstants.ACTION_MOVE);
  }

  public void autoscroll(Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left, outer.y + insets.top, outer.width
        - (insets.left + insets.right), outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
      Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left, cursorLocation.y - insets.top, insets.left
          + insets.right, insets.top + insets.bottom);
      scrollRectToVisible(scrollRect);
    }
  }

  public Insets getAutoscrollInsets() {
    return (autoscrollInsets);
  }

  public static DefaultMutableTreeNode makeDeepCopy(DefaultMutableTreeNode node) {
    DefaultMutableTreeNode copy = new DefaultMutableTreeNode(node.getUserObject());
    for (Enumeration e = node.children(); e.hasMoreElements();) {
      copy.add(makeDeepCopy((DefaultMutableTreeNode) e.nextElement()));
    }
    return (copy);
  }

}
